﻿import { Component, OnInit } from '@angular/core';
import { NavController } from 'ionic-angular';
import { PostPage } from '../post/post.page';
import { Post } from '../../models/post';
import { PostService} from '../../services/post.service';
import { Loading } from '../../components/loading';

@Component({
    selector: 'page-index',
    templateUrl: 'index.html'
})
export class IndexPage implements OnInit {

    posts: Post[];

    constructor(
        public navCtrl: NavController,
        public postServ: PostService,
        private loading: Loading,
        ) {
    }

    ngOnInit(): void {
        this.getPosts();
    }

    getPosts(): void {
        this.loading.presentLoading();
        this.postServ.getPosts()
        .then(posts => {
            this.posts = posts;
            this.loading.dismiss();
        });
    }

    openPost(post:Post):void {
        this.navCtrl.push(PostPage,{post: post});
    }

    doInfinite(infiniteScroll) {
        console.log('Begin async operation');
        setTimeout(() => {
            this.postServ.getPosts().then((posts) => {
                for(let post of posts) {
                this.posts.push(post);
                }
            });
            console.log('Async operation has ended');
            infiniteScroll.complete();
        }, 500);
    }

    doRefresh(refresher) {
        console.log('Begin async operation', refresher);
        setTimeout(() => {
            console.log('Async operation has ended');
            refresher.complete();
        }, 2000);
    }
    
}
